/*******************以下代码实现sessionStorage数据共享 START***********************/
var waitCopySessionStorageFinish = false;
if (!sessionStorage.length) {
    // 这个调用能触发目标事件，从而达到共享数据的目的
    localStorage.setItem('getSessionStorage', Date.now());
}
window.addEventListener('storage', function(event) {
    if (event.key == 'getSessionStorage') {
        // 已存在的标签页会收到这个事件
        localStorage.setItem('sessionStorageData', JSON.stringify(sessionStorage));
        localStorage.removeItem('sessionStorageData');
    } else if (event.key == 'sessionStorageData' && !sessionStorage.length) {
        // 新开启的标签页会收到这个事件
        let data = JSON.parse(event.newValue);
                // value;
        for (key in data) {
            sessionStorage.setItem(key, data[key]);
        }
        location.reload()
    }
});
/*******************以上代码实现sessionStorage数据共享 END***********************/

/**
 * 判断年份是否为润年
 *
 * @param {Number} year
 */
 function isLeapYear (year) {
    return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
/**
 * 获取某一年份的某一月份的天数
 *
 * @param {Number} year
 * @param {Number} month
 */
 function getMonthDays(year, month) {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (isLeapYear(year) ? 29 : 28);
}
 /**
 * 获取某年的某天是第几周
 * @param {Number} y
 * @param {Number} m
 * @param {Number} d
 * @returns {Number}
 */
function getWeekNumber(y, m, d) {
    var now = new Date(y, m - 1, d),
        year = now.getFullYear(),
        month = now.getMonth(),
        days = now.getDate();
    //那一天是那一年中的第多少天
    for (var i = 0; i < month; i++) {
        days += getMonthDays(year, i);
    }

    //那一年第一天是星期几
    var yearFirstDay = new Date(year, 0, 1).getDay() || 7;

    var week = null;
    if (yearFirstDay == 1) {
        week = Math.ceil(days / yearFirstDay);
    } else {
        days -= (7 - yearFirstDay + 1);
        week = Math.ceil(days / 7) + 1;
    }

    return week;
}

/*
 * 深度克隆，防止对象共享内存地址
 */
function deep_clone (obj) {
    var _tmp,result;
    _tmp = JSON.stringify(obj);
    result = JSON.parse(_tmp);
    return result;
}
/*
 * 判断是否为空
 */
function is_empty( obj ){
    if( typeof obj == "undefined"  ){
        return true;
    }else if( obj == null ){
        return true;
    }else if ( trim(obj.toString()) == "" ){
        return true;
    }else if( typeof(obj) == 'object' && ( Object.getOwnPropertyNames(obj).length === 0 || ( Object.getOwnPropertyNames(obj).length === 1 &&  Object.getOwnPropertyNames(obj).indexOf('__ob__') > -1   ) || ( Object.getOwnPropertyNames(obj).length === 1 &&  Object.getOwnPropertyNames(obj).indexOf('__proto__') > -1   ) )  ){
        return true;
    }else if( obj.length === 0 || (obj.length === 1 && obj.indexOf('__ob__') > -1 )){
        return true;
    }else{
        return false;
    }
    function trim(str){
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }
}

function in_array(ele,arr,inx = null){
    for(i=0;i<arr.length;i++) {
        if( is_empty(inx) ){
            if(arr[i] == ele){
                return true;
            }
        }else{
            if( arr[i][inx] == ele ){
                return true;
            }
        }

    }
     return false
}

function PrefixInteger(num, length) {
 return (Array(length).join('0') + num).slice(-length);
}

window.validateName = (name) =>{

    if(name === null || name === undefined) return false

    let appell = /^[\S]{1,}$/

    return name.toString().match(appell)
}

window.isEmpty = (value) => {
    return value !== '' && value !== undefined && value !== null && value.constructor !== Array
}

window.validateIp = (ip)=>{

    if(ip === null || ip === undefined) return false

    let preg = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/

    return ip.toString().match(preg)

}

window.validateNumber = (vol) =>{

    if(vol === null || vol === undefined) return false

    let num = /^\d{11,11}$/

    return vol.toString().match(num)
}

window.validateEmail = (em) =>{

    if(em === null || em === undefined) return false

    let email = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/

    return em.toString().match(email)
}

window.validatePort = (number) =>{

    if(number === null || number === undefined) return false

    let port = /^\d+$/

    return number.toString().match(port)
}

//时间戳转日期
function timestampToTime( timestamp = null ) {
    if( typeof(timestamp) == 'number' ){
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    }else if(typeof(timestamp) == 'object' && !is_empty(timestamp) ){
        var date = new Date(timestamp);//标准日期格式
    }else{
        var date = new Date();
    }

    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = (date.getDate() < 10 ? '0'+ date.getDate() : date.getDate()) + ' ' ;
    h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':';
    m = (date.getMinutes() < 10 ? '0'+ date.getMinutes() : date.getMinutes()) + ':';
    s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
    return Y+M+D+h+m+s;
}
/**
 * 转换机读尺寸(Byte)为人读尺寸（K，M，G，T，P）
 */
function hfsize( bytes, decimals ) {
    bytes = parseInt( bytes );
    decimals = parseInt( decimals );
    if ( decimals > 8 ) {
        decimals = 8;
    }
    if ( isNaN( decimals ) ) {
        decimals = 2;
    }
    var sz = [ 'B', 'K', 'M', 'G', 'T', 'P' ];
    var factor = Math.floor( ( ( bytes + '' ).length - 1 ) / 3 );
    var result = bytes / Math.pow( 1024, factor ) + '';
    var index = result.indexOf( '.' );
    if ( index == -1 ) {
        index = result.length - decimals - 1;
    }
    result = result.substr( 0, index + decimals + 1 );
    return result + sz[ factor ];
}
/**
 * 格式化秒数
 * @return Array
 */
function formatSeconds( value ) {
    var second = parseInt( value ); // 秒
    var minute = 0; // 分
    var hour = 0; // 小时
    var result = [];
    if ( second > 60 ) {
        minute = parseInt( second / 60 );
        second = parseInt( second % 60 );
        if ( minute > 60 ) {
            hour = parseInt( minute / 60 );
            minute = parseInt( minute % 60 );
        }
    }
    result[ 'second' ] = str_pad_left( parseInt( second ).toString(), 2, '0' );
    result[ 'minute' ] = str_pad_left( parseInt( minute ).toString(), 2, '0' );
    result[ 'hour' ] = str_pad_left( parseInt( hour ).toString(), 2, '0' );
    return result;
}



function str_pad_left( str, width, pad_char ) {
    return str.length < width ? str_pad_left( pad_char + str, width, pad_char ) : str;
}
//提取二维数组中某一列的值
function getOneColumn( arrrr , filed ){
    if( !arrrr[0].hasOwnProperty(filed) || is_empty(arrrr) || is_empty(filed) ){
        return [];
    }
    var re_arr = [];
    for (var i = 0; i < arrrr.length; i++) {
       re_arr.push(arrrr[i][filed])
    }
    return re_arr;
}
function arrayIntersection() {
    var result = new Array();
    var obj = {};
    for (var i = 0; i < arguments.length; i++) {
        for (var j = 0; j < arguments[i].length; j++) {
            var str = arguments[i][j];
            if (!obj[str]) {
                obj[str] = 1;
            }
            else {
                obj[str]++;
                if (obj[str] == arguments.length)
                {
                    result.push(str);
                }
            }//end else
        }//end for j
    }//end for i
    return result;
}

/**
 * 将秒数换成时分秒格式
 * 作者：龙周峰
 */
function formatSecondsToHour(val) {
    var h = Math.floor(val / 3600),
        m = Math.floor((val / 60 % 60)),
        s = Math.floor((val % 60));
    if(h < 10){
        h = '0'+h;
    }
    if(m < 10){
        m = '0'+m;
    }
    if(s < 10){
        s = '0'+s;
    }
    return h + ":" + m + ":" + s ;
}
/*检测值是否为空*/
function checkSpace(val) {
    if (val && !Number.isInteger(val)) {
        return val.trim() ? val : '';
    }
    return val;
}

/**
 * 获取当前周从星期一到星期天的日期
 * @param {String} val 日期
 */
function getWeekDay(val) {
    const dateOfToday = new Date(val).getTime();
    const dayOfToday = (new Date(val).getDay() + 7 - 1) % 7
    const daysOfThisWeek = Array.from(new Array(7)).map((_, i) => {
        const date = new Date(dateOfToday + (i - dayOfToday) * 1000 * 60 * 60 * 24);

        return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
    })
    
    return daysOfThisWeek;
}
/**
* 处理接口规范的数据兼容旧版本
* @param {Object} data 
*/
function handleResponseData( data, name){
    if (name === 'need') {
        var responseData = deep_clone( data.data );
        responseData.code = data.return;
        responseData.msg = data.return_message;
        return responseData;
    } else {
        return data;
    }
}